package util.concurrent;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 李栋
 * @version 1.0.0
 * @className ConditionTest.java
 * @createTime 2021年08月06日 20:51:00
 */
public class ConditionTest {

    private static final Logger logger = LoggerFactory.getLogger(ConditionTest.class);

    /**
     * Condition 是一个多线程间协调通信的工具类，使得某个，或者某些线程一起等待某个条件（Condition）,
     * 只有当该条件具备( signal 或者 signalAll方法被带调用)时 ，这些等待线程才会被唤醒，从而重新争夺锁。
     *
     * @throws InterruptedException
     */
    @Test
    public void test1() throws InterruptedException {
        Lock lock = new ReentrantLock();
        Condition condition = lock.newCondition();
        new Thread(() -> {
            try {
                lock.tryLock();
                logger.info("线程：{} 等待信号", Thread.currentThread().getId());
                condition.await();
            } catch (InterruptedException e) {
                logger.error(e.getMessage(), e);
            } finally {
                logger.info("线程：{} 得到信号", Thread.currentThread().getId());
                lock.unlock();
            }
        }).start();
        TimeUnit.MILLISECONDS.sleep(10);
        new Thread(() -> {
            lock.tryLock();
            logger.info("线程：{} 拿到锁", Thread.currentThread().getId());
            condition.signal();
            logger.info("线程：{} 发出信号", Thread.currentThread().getId());
            lock.unlock();
        }).start();
        TimeUnit.SECONDS.sleep(2);
    }

}
